package guoanmaker.personal.business.service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import javax.validation.constraints.Null;

import guoanmaker.personal.business.model.*;
import guoanmaker.personal.business.repository.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import guoanmaker.personal.business.dao.KeyValueDao;
import guoanmaker.personal.business.dao.PersonalOrderFormDao;

import guoanmaker.personal.business.model.MessageType;
import guoanmaker.personal.business.model.OperatorCoupons;
import guoanmaker.personal.business.model.OperatorSecckill;
import guoanmaker.personal.business.model.PayInfo;
import guoanmaker.personal.business.model.PersonalInvoice;
import guoanmaker.personal.business.model.PersonalUserCoupon;
import guoanmaker.personal.business.model.ProvideCommodity;
import guoanmaker.personal.business.model.ProvideCommodityServiceRange;
import guoanmaker.personal.business.model.ProvideOrderForm;
import guoanmaker.personal.business.model.ReturnResult;

import guoanmaker.personal.business.modelnobind.Coupons;
import guoanmaker.personal.business.modelnobind.JsonAnalyze;
import guoanmaker.personal.business.modelnobind.ProvideOrderFormForOrder;
import guoanmaker.personal.helper.common.AjaxJson;
import guoanmaker.personal.helper.common.abstractobj.ApiController;
import guoanmaker.personal.helper.common.util.SystemHelper;
import lombok.experimental.PackagePrivate;

/**
 * 
* @ClassName: PersonalOrderFormService 
* @Description: 订单service
* @author Yvonne_MGL
* @date 2017年7月12日 下午2:03:21 
*  
 */
@Service
public class PersonalOrderFormService {
	@Resource
	private ProvideCommodityRepository provideCommodityRepository;
	
	@Resource
	private PersonalOrderFormDao personalOrderFormDao;
	
	@Resource
	private PersonalOrderFormRepository personalOrderFormRepository;
	
	@Resource
	private PersonalUserRepository personalUserRepository;
	
	@Resource
	private PersonalInvoiceRepository personalInvoiceRepository;
	
	@Resource
	private PersonalCodeService personalCodeService;
	
	@Resource
	private PersonalUserCouponRepository personalUserCouponRepository;
	
	@Resource
	private OperatorCouponsRepository operatorCouponsRepository;
	
	@Resource
	private ProvideCommodityServiceRangeRepository provideCommodityServiceRangeRepository;
	
	@Resource
	private PersonalOrderFormService personalOrderFormService;
	
	@Resource
	private MessageTypeRepository messageTypeRepository;
	
	@Resource
	private OperatorServerClassService operatorServerClassService;
	
	@Resource
	private OperatorSecckillRepository operatorSecckillRepository;
	
	@Resource
	private KeyValueDao keyValueDao;

	@Resource
	private OperatorActivityEnlistRepository operatorActivityEnlistRepository;
	
	/**
	 * 
	* @Description: 创建一口价商品订单 
	* @param commodityid 商品id
	* @param contactPerson 联系人
	* @param contactNumber 联系电话
	* @param requirementDescription 需求描述
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月12日 下午3:14:54     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult createNotBargainingOrder(String userid,String commodityid,String contactPerson,String contactNumber,String requirementDescription,String placeOrderType,String serverPlace,String rangeid){
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=new ProvideOrderForm();
		ProvideCommodity provideCommodity=provideCommodityRepository.findOne(commodityid);
		if(provideCommodity!=null&&provideCommodity.getStock()!=null&&provideCommodity.getStock()>0&&provideCommodity.getCommodityState()==2){
			provideCommodity.setStock(provideCommodity.getStock()-1);
			if(provideCommodity.getSalesVolume()==null){
				provideCommodity.setSalesVolume(1);
			}else{
				provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()+1);
			}
			if(provideCommodity.getStock()==0){
				provideCommodity.setCommodityState(4);
			}
			if(provideCommodity.getStock()==0&&provideCommodity.getType().equals("3")){
				provideCommodity.setCommodityState(7);
			}
			provideCommodityRepository.save(provideCommodity);
			if(rangeid!=null&&!rangeid.equals("")){
				ProvideCommodityServiceRange range=provideCommodityServiceRangeRepository.findOne(rangeid);
				if(range!=null){
					orderForm.setRealPrice(range.getFinalPrice());
					orderForm.setTruePrice(range.getFinalPrice());
					orderForm.setUnitPrice(range.getCommodityPrice());
				}else{
					orderForm.setRealPrice(provideCommodity.getFinalPrice());
					orderForm.setTruePrice(provideCommodity.getFinalPrice());
					orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
				}
			}else{
				orderForm.setRealPrice(provideCommodity.getFinalPrice());
				orderForm.setTruePrice(provideCommodity.getFinalPrice());
				orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
			}
			
			orderForm.setOrderNumber(personalOrderFormDao.getOrderNumber());
			orderForm.setOrderStatus("1");
			orderForm.setContactPerson(contactPerson);
			orderForm.setContactNumber(contactNumber);
			orderForm.setRequirementDescription(requirementDescription);
			orderForm.setPlaceOrderTime(new Date());
			orderForm.setQuantity(1);
			orderForm.setOrderType("1");
			orderForm.setUser(personalUserRepository.findOne(userid));
			orderForm.setCommodity(provideCommodity);
			orderForm.setIsRead("0");
			orderForm.setPlaceOrderType(placeOrderType);
			orderForm.setServerPlace(serverPlace);
			personalOrderFormRepository.save(orderForm);
			returnResult.setKey("success");
    		returnResult.setValue(orderForm.getId());
		}else{
			if(provideCommodity==null){
				returnResult.setKey("error");
				returnResult.setValue("商品不存在");
			}else if(provideCommodity.getStock()==null||provideCommodity.getStock()<=0){
				returnResult.setKey("error");
				returnResult.setValue("商品库存不足");
			}else if(provideCommodity.getCommodityState()==4){
				returnResult.setKey("error");
				returnResult.setValue("商品已下架");
			}else if(provideCommodity.getCommodityState()==5){
				returnResult.setKey("error");
				returnResult.setValue("商品已被冻结");
			}else if(provideCommodity.getCommodityState()==6){
				returnResult.setKey("error");
				returnResult.setValue("商品已被删除");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("商品当前状态不允许下单");
			}
			
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 创建议价商品订单 
	* @param commodityid 商品id
	* @param contactPerson 联系人
	* @param contactNumber 联系电话
	* @param requirementDescription 需求描述
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月12日 下午4:13:20     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult createBargainingOrder(String userid,String commodityid,String contactPerson,String contactNumber,String requirementDescription,String placeOrderType,String serverPlace)throws Exception{
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=new ProvideOrderForm();
		ProvideCommodity provideCommodity=provideCommodityRepository.findOne(commodityid);
		if(provideCommodity!=null&&provideCommodity.getStock()!=null&&provideCommodity.getStock()>0&&provideCommodity.getCommodityState()==2){
			provideCommodity.setStock(provideCommodity.getStock()-1);
			if(provideCommodity.getSalesVolume()==null){
				provideCommodity.setSalesVolume(1);
			}else{
				provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()+1);
			}
			if(provideCommodity.getStock()==0){
				provideCommodity.setCommodityState(4);
			}
			provideCommodityRepository.save(provideCommodity);
			orderForm.setOrderNumber(personalOrderFormDao.getOrderNumber());
			orderForm.setOrderStatus("14");
			orderForm.setContactPerson(contactPerson);
			orderForm.setContactNumber(contactNumber);
			orderForm.setRequirementDescription(requirementDescription);
			orderForm.setPlaceOrderTime(new Date());
			orderForm.setQuantity(1);
			orderForm.setOrderType("2");
			orderForm.setIsOverChangePrice("0");
			orderForm.setUser(personalUserRepository.findOne(userid));
			orderForm.setCommodity(provideCommodity);
			orderForm.setUnitPrice(provideCommodity.getStartingPrice());
			orderForm.setIsRead("0");
			orderForm.setPlaceOrderType(placeOrderType);
			orderForm.setServerPlace(serverPlace);
			personalOrderFormRepository.save(orderForm);
			MessageType messageType=new MessageType();
			messageType.setType(1);
			messageType.setSourceid(orderForm.getId());
			messageType.setIsread(0);
			messageType.setDecribestr("您有一笔【"+provideCommodity.getCommodityName()+"】订单待沟通，需您处理。");
			messageType.setCreatedate(new Date());
			messageType.setBusinessid(provideCommodity.getProviderBusiness().getId());
			messageTypeRepository.save(messageType);
			
			returnResult.setKey("success");
    		returnResult.setValue(orderForm.getId());
    		
    		String message="尊敬的服务商用户您好，您有新的询价订单，请您及时与用户进行沟通确认，详情请登录服务商端查看，感谢您的支持与信任。";
    		String telephone=orderForm.getCommodity().getProviderBusiness().getLicensPhone();
    		personalCodeService.sendMessage(telephone, message);
    		
		}else{
			if(provideCommodity==null){
				returnResult.setKey("error");
				returnResult.setValue("商品不存在");
			}else if(provideCommodity.getStock()==null||provideCommodity.getStock()<=0){
				returnResult.setKey("error");
				returnResult.setValue("商品库存不足");
			}else if(provideCommodity.getCommodityState()==4){
				returnResult.setKey("error");
				returnResult.setValue("商品已下架");
			}else if(provideCommodity.getCommodityState()==5){
				returnResult.setKey("error");
				returnResult.setValue("商品已被冻结");
			}else if(provideCommodity.getCommodityState()==6){
				returnResult.setKey("error");
				returnResult.setValue("商品已被删除");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("商品当前状态不允许下单");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 创建工位租用订单
	* @param userid 用户id
	* @param commodityid 商品id
	* @param contactPerson 联系人
	* @param contactNumber 联系电话
	* @param days 租用天数
	* @param quantity 租用数量
	* @param remark 备注
	* @param placeOrderType 下单类型
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年8月23日 下午2:34:50     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult createSeatLeaseOrder(String userid,String commodityid,String contactPerson,String contactNumber,String beginDate,String endDate,int quantity,String remark,String placeOrderType,String serverPlace)throws Exception{
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=new ProvideOrderForm();
		ProvideCommodity provideCommodity=provideCommodityRepository.findOne(commodityid);
		if(provideCommodity!=null&&provideCommodity.getStock()!=null&&(provideCommodity.getStock()-quantity)>=0&&provideCommodity.getCommodityState()==2){
			int days=SystemHelper.daysBetween(beginDate, endDate);
			if(days<=0){
				returnResult.setKey("error");
				returnResult.setValue("租用天数不符合要求");
			}else{
				provideCommodity.setStock(provideCommodity.getStock()-quantity);
				if(provideCommodity.getSalesVolume()==null){
					provideCommodity.setSalesVolume(quantity);
				}else{
					provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()+quantity);
				}
				if(provideCommodity.getStock()==0){
					provideCommodity.setCommodityState(4);
				}
				provideCommodityRepository.save(provideCommodity);
				orderForm.setRealPrice(provideCommodity.getFinalPrice()*quantity*days);
				orderForm.setTruePrice(provideCommodity.getFinalPrice()*quantity*days);
				orderForm.setRentedBeginDate(beginDate);
				orderForm.setRentedEndDate(endDate);
				orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
				orderForm.setOrderNumber(personalOrderFormDao.getOrderNumber());
				orderForm.setOrderStatus("1");
				orderForm.setContactPerson(contactPerson);
				orderForm.setContactNumber(contactNumber);
				orderForm.setRequirementDescription(remark);
				orderForm.setPlaceOrderTime(new Date());
				orderForm.setQuantity(quantity);
				orderForm.setOrderType("3");
				orderForm.setUser(personalUserRepository.findOne(userid));
				orderForm.setCommodity(provideCommodity);
				orderForm.setIsRead("0");
				orderForm.setPlaceOrderType(placeOrderType);
				orderForm.setServerPlace(serverPlace);
				personalOrderFormRepository.save(orderForm);
				returnResult.setKey("success");
	    		returnResult.setValue(orderForm.getId());
			}
			
			
		}else{
			if(provideCommodity==null){
				returnResult.setKey("error");
				returnResult.setValue("商品不存在");
			}else if(provideCommodity.getStock()==null||provideCommodity.getStock()-quantity<0){
				returnResult.setKey("error");
				returnResult.setValue("商品库存不足");
			}else if(provideCommodity.getCommodityState()==4){
				returnResult.setKey("error");
				returnResult.setValue("商品已下架");
			}else if(provideCommodity.getCommodityState()==5){
				returnResult.setKey("error");
				returnResult.setValue("商品已被冻结");
			}else if(provideCommodity.getCommodityState()==6){
				returnResult.setKey("error");
				returnResult.setValue("商品已被删除");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("商品当前状态不允许下单");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 创建咨询订单 
	* @param commodityid 商品id
	* @param contactPerson 联系人
	* @param contactNumber 联系电话
	* @param requirementDescription 需求描述
	* @param enterpriseName 企业名称
	* @param position 职位
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年12月15日 上午9:57:20     
	* @return ReturnResult 
	 */
	@Transactional
	public ReturnResult createAdvisoryOrder(String userid,String commodityid,String contactPerson,String contactNumber,String requirementDescription,
			String placeOrderType,String serverPlace,String enterpriseName,String position)throws Exception{
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=new ProvideOrderForm();
		ProvideCommodity provideCommodity=provideCommodityRepository.findOne(commodityid);
		if(provideCommodity!=null&&provideCommodity.getStock()!=null&&provideCommodity.getStock()>0&&provideCommodity.getCommodityState()==2){
			provideCommodity.setStock(provideCommodity.getStock()-1);
			if(provideCommodity.getSalesVolume()==null){
				provideCommodity.setSalesVolume(1);
			}else{
				provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()+1);
			}
			if(provideCommodity.getStock()==0){
				provideCommodity.setCommodityState(4);
			}
			provideCommodityRepository.save(provideCommodity);
			orderForm.setOrderNumber(personalOrderFormDao.getOrderNumber());
			orderForm.setOrderStatus("14");
			orderForm.setContactPerson(contactPerson);
			orderForm.setContactNumber(contactNumber);
			orderForm.setRequirementDescription(requirementDescription);
			orderForm.setPlaceOrderTime(new Date());
			orderForm.setQuantity(1);
			orderForm.setOrderType("4");
			orderForm.setIsOverChangePrice("0");
			orderForm.setUser(personalUserRepository.findOne(userid));
			orderForm.setCommodity(provideCommodity);
			orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
			orderForm.setIsRead("0");
			orderForm.setPlaceOrderType(placeOrderType);
			orderForm.setServerPlace(serverPlace);
			orderForm.setEnterpriseName(enterpriseName);
			orderForm.setPosition(position);
			personalOrderFormRepository.save(orderForm);
			MessageType messageType=new MessageType();
			messageType.setType(1);
			messageType.setSourceid(orderForm.getId());
			messageType.setIsread(0);
			messageType.setDecribestr("您有一笔【"+provideCommodity.getCommodityName()+"】订单待沟通，需您处理。");
			messageType.setCreatedate(new Date());
			messageType.setBusinessid(provideCommodity.getProviderBusiness().getId());
			messageTypeRepository.save(messageType);
			
			returnResult.setKey("success");
    		returnResult.setValue(orderForm.getId());
    		
    		String message="尊敬的服务商用户您好，您有新的询价订单等待您的处理，请您及时与用户进行沟通确认，预约详情请登录服务商端查看。感谢您对“国安创客”平台的支持与信任。";
    		String telephone=orderForm.getCommodity().getProviderBusiness().getLicensPhone();
    		personalCodeService.sendMessage(telephone, message);
    		
		}else{
			if(provideCommodity==null){
				returnResult.setKey("error");
				returnResult.setValue("商品不存在");
			}else if(provideCommodity.getStock()==null||provideCommodity.getStock()<=0){
				returnResult.setKey("error");
				returnResult.setValue("商品库存不足");
			}else if(provideCommodity.getCommodityState()==4){
				returnResult.setKey("error");
				returnResult.setValue("商品已下架");
			}else if(provideCommodity.getCommodityState()==5){
				returnResult.setKey("error");
				returnResult.setValue("商品已被冻结");
			}else if(provideCommodity.getCommodityState()==6){
				returnResult.setKey("error");
				returnResult.setValue("商品已被删除");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("商品当前状态不允许下单");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 创建咨询订单 
	* @param commodityid 商品id
	* @param contactPerson 联系人
	* @param contactNumber 联系电话
	* @param requirementDescription 需求描述
	* @param enterpriseName 企业名称
	* @param position 职位
	* @param @return
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2018年1月8日 上午11:03:40     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult createAdvisoryOrderFixedPrice(String userid,String commodityid,String contactPerson,String contactNumber,String requirementDescription,
			String placeOrderType,String serverPlace,String enterpriseName,String position)throws Exception{
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=new ProvideOrderForm();
		ProvideCommodity provideCommodity=provideCommodityRepository.findOne(commodityid);
		if(provideCommodity!=null&&provideCommodity.getStock()!=null&&provideCommodity.getStock()>0&&provideCommodity.getCommodityState()==2){
			provideCommodity.setStock(provideCommodity.getStock()-1);
			if(provideCommodity.getSalesVolume()==null){
				provideCommodity.setSalesVolume(1);
			}else{
				provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()+1);
			}
			if(provideCommodity.getStock()==0){
				provideCommodity.setCommodityState(4);
			}
			provideCommodityRepository.save(provideCommodity);
			orderForm.setOrderNumber(personalOrderFormDao.getOrderNumber());
			orderForm.setRealPrice(provideCommodity.getFinalPrice());
			orderForm.setTruePrice(provideCommodity.getFinalPrice());
			orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
			orderForm.setOrderStatus("1");
			orderForm.setContactPerson(contactPerson);
			orderForm.setContactNumber(contactNumber);
			orderForm.setRequirementDescription(requirementDescription);
			orderForm.setPlaceOrderTime(new Date());
			orderForm.setQuantity(1);
			orderForm.setOrderType("4");
			orderForm.setUser(personalUserRepository.findOne(userid));
			orderForm.setCommodity(provideCommodity);
			orderForm.setIsRead("0");
			orderForm.setPlaceOrderType(placeOrderType);
			orderForm.setServerPlace(serverPlace);
			orderForm.setEnterpriseName(enterpriseName);
			orderForm.setPosition(position);
			personalOrderFormRepository.save(orderForm);
			returnResult.setKey("success");
    		returnResult.setValue(orderForm.getId());
    		
		}else{
			if(provideCommodity==null){
				returnResult.setKey("error");
				returnResult.setValue("商品不存在");
			}else if(provideCommodity.getStock()==null||provideCommodity.getStock()<=0){
				returnResult.setKey("error");
				returnResult.setValue("商品库存不足");
			}else if(provideCommodity.getCommodityState()==4){
				returnResult.setKey("error");
				returnResult.setValue("商品已下架");
			}else if(provideCommodity.getCommodityState()==5){
				returnResult.setKey("error");
				returnResult.setValue("商品已被冻结");
			}else if(provideCommodity.getCommodityState()==6){
				returnResult.setKey("error");
				returnResult.setValue("商品已被删除");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("商品当前状态不允许下单");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 根据用户id和订单状态查询订单 
	* @param orderStatus 订单状态
	* @param userid 用户id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月12日 下午4:40:40     
	* @return List<ProvideOrderFormForOrder>    
	* @throws 
	 */
	public List<ProvideOrderFormForOrder> findByProperties(String orderStatus, String userid) {
		return personalOrderFormDao.findByProperties(orderStatus, userid);
	}
	
	/**
	 * 
	* @Description: 根据id获取订单详情 
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月12日 下午4:41:17     
	* @return ProvideOrderFormForOrder    
	* @throws 
	 */
	public ProvideOrderFormForOrder findByid(String id)  throws Exception{
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(id);
		if(orderForm!=null&&orderForm.getDefrayNumber()!=null){
			personalOrderFormService.overPay(id, orderForm.getDefrayNumber());
		}
		
		return personalOrderFormDao.findByid(id);
	}
	
	/**
	 * 
	* @Description: 修改订单为完成支付状态
	* @param id 订单id
	* @param defrayNumber 支付单号
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 上午10:12:44     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult overPay(String id,String defrayNumber) throws Exception{
		ReturnResult returnResult = new ReturnResult();
		
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("1")&&!orderForm.getOrderStatus().equals("7")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				
				String url=ApiController.PAY_URL+"select/payorder";
				String param="isJava=1&pingId="+defrayNumber;
				String result=SystemHelper.httpGetHelper(url, param);
				if(result!=null&&result.equals("1")){
					if(orderForm.getCommodity().getType().equals("3")||orderForm.getPlaceOrderType().equals("3")){
						orderForm.setOrderStatus("6");
					}else{
						orderForm.setOrderStatus("2");
					}
					orderForm.setDefrayTime(new Date());
					orderForm.setDefrayNumber(defrayNumber);
					orderForm.setIsRead("0");
					if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
						//price=price-Integer.parseInt(new DecimalFormat("#").format(orderForm.getPreferentialMoney()*100));
						if(orderForm.getCouponid()==null||!orderForm.getCouponid().equals("")){
							String ids[]=orderForm.getCouponid().split(",");
							if(ids.length>0){
								for (int i = 0; i < ids.length; i++) {
									PersonalUserCoupon puCoupon = personalUserCouponRepository.findOne(ids[i]);
									puCoupon.setIsUsed("1");
									personalUserCouponRepository.save(puCoupon);
									OperatorCoupons oCoupons=puCoupon.getOperatorCoupon();
									oCoupons.setBeenused(oCoupons.getBeenused()+1);
									operatorCouponsRepository.save(oCoupons);
								}
							}
						}
					}
					if(orderForm.getPaymentMethod()!=null&&(orderForm.getPaymentMethod().equals("wx_pub_qr")||orderForm.getPaymentMethod().equals("alipay_pc_direct")||
							orderForm.getPaymentMethod().equals("alipay")||orderForm.getPaymentMethod().equals("wx")||
							orderForm.getPaymentMethod().equals("wx_h5")||orderForm.getPaymentMethod().equals("wx_js")||orderForm.getPaymentMethod().equals("alipay_h5"))){
						
						//int price=Integer.parseInt((orderForm.getRealPrice() * 100 + "").substring(0, (orderForm.getRealPrice() * 100 + "").indexOf(".")));
						String aaDouble=new DecimalFormat("#").format(orderForm.getRealPrice()*100);
						int price=Integer.parseInt(aaDouble);
						
						Map map=JsonAnalyze.getJsonValues(orderForm.getCommodity().getProviderBusiness().getId());
						String totalBail=(String)map.get("totalBail");
						String bail_rate=(String)map.get("bail_rate");
						String commission_rate=(String)map.get("commission_rate");
						int sumBail=personalOrderFormDao.getSumBail(orderForm.getCommodity().getProviderBusiness().getId());
						if(orderForm.getPaymentMethod().equals("wx_pub_qr")||orderForm.getPaymentMethod().equals("wx")||orderForm.getPaymentMethod().equals("wx_h5")||orderForm.getPaymentMethod().equals("wx_js")){
							orderForm.setFee(new BigDecimal(orderForm.getRealPrice()*5.5/1000));
						}else if(orderForm.getPaymentMethod().equals("alipay_pc_direct")||orderForm.getPaymentMethod().equals("alipay")||orderForm.getPaymentMethod().equals("alipay_h5")){
							orderForm.setFee(new BigDecimal(orderForm.getRealPrice()*1/100));
						}
						
						if(totalBail!=null&&Integer.parseInt(totalBail)>sumBail){
							int rate=10;
							if(bail_rate!=null&&Integer.parseInt(bail_rate)>=0&&Integer.parseInt(bail_rate)<100){
								rate=Integer.parseInt(bail_rate);
							}
							int bail=0;
							if(price*rate/100<(Integer.parseInt(totalBail)-sumBail)){
								bail=price*rate/100;
							}else{
								bail=Integer.parseInt(totalBail)-sumBail;
							}
							Double double1=(double) bail;
							orderForm.setBail(new BigDecimal(double1/100));
							
							
						}
						int c_rate=10;
						if(commission_rate!=null&&Integer.parseInt(commission_rate)>=0&&Integer.parseInt(commission_rate)<100){
							c_rate=Integer.parseInt(commission_rate);
						}
						Double double2=(double) price*c_rate/100;
						orderForm.setCommission(new BigDecimal(double2/100));
						
					}
					personalOrderFormRepository.save(orderForm);
					
					MessageType messageType=new MessageType();
					messageType.setType(1);
					messageType.setSourceid(orderForm.getId());
					messageType.setIsread(0);
					messageType.setDecribestr("您有一笔【"+orderForm.getCommodity().getCommodityName()+"】订单待接单，需您处理。");
					messageType.setCreatedate(new Date());
					messageType.setBusinessid(orderForm.getCommodity().getProviderBusiness().getId());
					messageTypeRepository.save(messageType);
					
					returnResult.setKey("success");
		    		returnResult.setValue("完成支付");
		    		
		    		if(orderForm.getOrderType()!=null&&(orderForm.getOrderType().equals("1")||orderForm.getOrderType().equals("3"))){
		    			String telephone=orderForm.getCommodity().getProviderBusiness().getLicensPhone();
			    		Double p=orderForm.getRealPrice();
			    		if(orderForm.getSpikeid()!=null&&!orderForm.getSpikeid().equals("")){
			    			DecimalFormat df = new DecimalFormat("######0.00"); 
			    			p=Double.parseDouble(df.format(orderForm.getRealPrice()-orderForm.getPreferentialMoney()));
			    		}
		    			String message="尊敬的服务商用户您好，您有一笔新的订单，订单号："+orderForm.getOrderNumber()+"，请您及时处理（如24小时内未处理，系统将自动关闭），感谢您的支持。";
			    		personalCodeService.sendMessage(telephone, message);
		    		}
		    		
				}else{
					returnResult.setKey("error");
					returnResult.setValue("尚未支付");
				}
			}	
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 确认完成订单 
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL  
	* @date 2017年7月13日 上午11:18:30     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult confirmOrder(String id){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("4")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				orderForm.setOrderStatus("6");
				orderForm.setConfirmTime(new Date());
				orderForm.setIsRead("0");
				String url=ApiController.PAY_URL+"confirm/order";
				String param="isJava=1&id="+orderForm.getDefrayNumber();
				String json=SystemHelper.httpGetHelper(url, param);
				if(json.indexOf("SUCCESS")>0){
					personalOrderFormRepository.save(orderForm);
					returnResult.setKey("success");
		    		returnResult.setValue("完成服务成功");
				}else{
					returnResult.setKey("error");
					returnResult.setValue("访问财务接口异常");
				}
				
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 用户发起退款 
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 上午11:35:46     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult initiateRefunds(String id,Double amount,String refundsReason)throws Exception{
		
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(refundsReason==null){
				refundsReason="无";
			}
			if(!orderForm.getOrderStatus().equals("2")&&!orderForm.getOrderStatus().equals("3")&&!orderForm.getOrderStatus().equals("4")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				if(orderForm.getOrderStatus().equals("2")){
					//int price=Integer.parseInt((orderForm.getRealPrice()*100+"").substring(0, (orderForm.getRealPrice()*100+"").indexOf(".")));
					String aaDouble=new DecimalFormat("#").format(orderForm.getRealPrice()*100);
					int price=Integer.parseInt(aaDouble);
					PersonalUserCoupon puCoupon=null;
					if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
						price=price-Integer.parseInt(new DecimalFormat("#").format(orderForm.getPreferentialMoney()*100));
						puCoupon=personalUserCouponRepository.findOne(orderForm.getCouponid());
						puCoupon.setIsUsed("0");
					}
					
					String url=ApiController.PAY_URL+"askrefund";
					
					String param="isJava=1&id="+orderForm.getDefrayNumber()+"&ask_name="+orderForm.getUser().getUsername()
							+"&ask_amount="+price+"&ask_description="+URLEncoder.encode(refundsReason, "UTF-8");
					String json=SystemHelper.httpGetHelper(url, param);
					if(json.indexOf("SUCCESS")>0){
						Double preferentialMoney=0.00;
						if(puCoupon!=null){
							personalUserCouponRepository.save(puCoupon);
							OperatorCoupons oCoupons=puCoupon.getOperatorCoupon();
							oCoupons.setBeenused(oCoupons.getBeenused()-1);
							operatorCouponsRepository.save(oCoupons);
							preferentialMoney=orderForm.getPreferentialMoney();
						}
						orderForm.setOrderStatus("11");
						orderForm.setApplyforRefundsTime(new Date());
						orderForm.setIsRead("0");
						orderForm.setRefundsAmount(orderForm.getRealPrice()-preferentialMoney);
						orderForm.setFullOrPartRefunds("2");
						orderForm.setCommission(new BigDecimal(0.00));
						orderForm.setBail(new BigDecimal(0.00));
						orderForm.setPreferentialMoney(0.00);
						orderForm.setRealPrice(0.00);
						orderForm.setRefundsReason(refundsReason);
						personalOrderFormRepository.save(orderForm);
						ProvideCommodity provideCommodity=orderForm.getCommodity();
						if(provideCommodity.getStock()==null){
							provideCommodity.setStock(1);
						}else{
							provideCommodity.setStock(provideCommodity.getStock()+1);
						}
						if(provideCommodity.getCommodityState()==null||provideCommodity.getCommodityState()==0){
							provideCommodity.setSalesVolume(0);
						}else{
							provideCommodity.setSalesVolume(provideCommodity.getCommodityState()-1);
						}
						if(provideCommodity.getType().equals("3")&&provideCommodity.getCommodityState()==7&&provideCommodity.getRegistrationEndTime().after(new Date())){
							provideCommodity.setCommodityState(2);
						}
						provideCommodityRepository.save(provideCommodity);
						returnResult.setKey("success");
			    		returnResult.setValue("申请退款成功");
					}else{
						returnResult.setKey("error");
			    		returnResult.setValue("申请退款失败");
					}
				}else{
					Double preferentialMoney=0.00;
					if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
						preferentialMoney=orderForm.getPreferentialMoney();
					}
					DecimalFormat df = new DecimalFormat("######0.00"); 
					Double bDouble=Double.parseDouble(df.format(orderForm.getRealPrice()-preferentialMoney));
					if(amount==null||amount<=0||amount>bDouble){
						returnResult.setKey("error");
			    		returnResult.setValue("退款金额不正确");
					}else{
						orderForm.setOrderStatus("5");
						orderForm.setApplyforRefundsTime(new Date());
						orderForm.setIsRead("0");
						orderForm.setRefundsAmount(amount);
						orderForm.setRefundsReason(refundsReason);
						if(amount==orderForm.getRealPrice()-preferentialMoney){
							orderForm.setFullOrPartRefunds("2");
						}else{
							orderForm.setFullOrPartRefunds("1");
						}
						personalOrderFormRepository.save(orderForm);
						
						MessageType messageType=new MessageType();
						messageType.setType(1);
						messageType.setSourceid(orderForm.getId());
						messageType.setIsread(0);
						messageType.setDecribestr("您有一笔【"+orderForm.getCommodity().getCommodityName()+"】订单待退款，需您处理。");
						messageType.setCreatedate(new Date());
						messageType.setBusinessid(orderForm.getCommodity().getProviderBusiness().getId());
						messageTypeRepository.save(messageType);
						
						returnResult.setKey("success");
			    		returnResult.setValue("申请退款成功");
			    		
			    		String telephone=orderForm.getCommodity().getProviderBusiness().getLicensPhone();
			    		String message="尊敬的服务商用户您好，有用户发起退款订单，用户发起一笔退款申请，请您与3个工作日内及时处理，感谢您的支持。";
			    		personalCodeService.sendMessage(telephone, message);
					}
				}
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 用户申请已完成或者退款完成的订单开发票 
	* @param orderid 订单id
	* @param invoiceid 用户发票id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月27日 下午4:31:55     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult getInvoice(String orderid,String invoiceid,String addressid){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(orderid);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			PersonalInvoice  personalInvoice=personalInvoiceRepository.findOne(invoiceid);
			if(personalInvoice==null){
				returnResult.setKey("error");
	    		returnResult.setValue("发票不存在");
			}else{
				if(orderForm.getInvoiceState()!=null&&(orderForm.getInvoiceState().equals("0")||orderForm.getInvoiceState().equals("1"))){
					returnResult.setKey("error");
		    		returnResult.setValue("此订单已申请过发票");
				}else{
					if(orderForm.getOrderStatus().equals("13")||orderForm.getOrderStatus().equals("6")||(orderForm.getOrderStatus().equals("8")&&orderForm.getFullOrPartRefunds()!=null&&orderForm.getFullOrPartRefunds().equals("1"))&&(orderForm.getOrderStatus().equals("12")&&orderForm.getFullOrPartRefunds()!=null&&orderForm.getFullOrPartRefunds().equals("1"))){
						orderForm.setInvoiceState("0");
						orderForm.setInvoiceid(invoiceid);
						orderForm.setAddressid(addressid);
						personalOrderFormRepository.save(orderForm);
						MessageType messageType=new MessageType();
						messageType.setType(4);
						messageType.setSourceid(orderForm.getId());
						messageType.setIsread(0);
						messageType.setDecribestr("有用户对【"+orderForm.getOrderNumber()+"】索取发票，需您处理。");
						messageType.setCreatedate(new Date());
						messageType.setBusinessid(orderForm.getCommodity().getProviderBusiness().getId());
						messageTypeRepository.save(messageType);
						returnResult.setKey("success");
			    		returnResult.setValue("申请开发票成功");
					}else{
						returnResult.setKey("error");
			    		returnResult.setValue("订单状态不允许此操作");
					}
				}
				
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 发起支付
	* @param orderid 订单id
	* @param channel 支付方式
	* @param @return
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年7月30日 上午11:10:56     
	* @return Map    
	* @throws 
	 */
	@Transactional
	public Map initiatePay(String orderid,String channel,String backUrl) throws Exception{
		Map map=new HashMap();
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(orderid);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("1")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				String aaDouble=new DecimalFormat("#").format(orderForm.getRealPrice()*100);
				int price=Integer.parseInt(aaDouble);
				String card_type="0";
				int preferentialMoney=0;
				if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
					//price=price-Integer.parseInt((orderForm.getPreferentialMoney() * 100 + "").substring(0, (orderForm.getPreferentialMoney() * 100 + "").indexOf(".")));
					card_type="1";
					preferentialMoney=Integer.parseInt(new DecimalFormat("#").format(orderForm.getPreferentialMoney()*100));
				}
				String back_url="";
				if(backUrl!=null&&!backUrl.equals("")){
					back_url=URLEncoder.encode(backUrl, "UTF-8");
				}
				String url=ApiController.PAY_URL+"pay";
				if(price==preferentialMoney){
					channel="free";
				}
				String param="uid="+orderForm.getUser().getId()+"&systemCode=10&platOrderId="+
				orderForm.getId()+"&channel="+channel+"&amount="+price+"&card_type="+card_type+"&card_amount="+preferentialMoney+"&originalId="+orderForm.getCommodity().getProviderBusiness().getId()+
				"&companyName="+URLEncoder.encode(orderForm.getCommodity().getProviderBusiness().getBusinessName(), "UTF-8")+"&companyTitle="+
				URLEncoder.encode(orderForm.getCommodity().getProviderBusiness().getCompanyName(),"UTF-8")+"&isJava=1&back_url="+back_url;
				String json=SystemHelper.httpGetHelper(url, param);
				if(json.indexOf("SUCCESS")>0){
					PayInfo payInfo=new PayInfo();
					payInfo=SystemHelper.getPayInfo(json,channel);
					map.put("pay", payInfo);
					orderForm.setDefrayNumber(payInfo.getId());
					orderForm.setPaymentMethod(channel);
					personalOrderFormRepository.save(orderForm);
					returnResult.setKey("success");
		    		returnResult.setValue("发起支付成功");
				}else{
					returnResult.setKey("error");
					returnResult.setValue("发起支付失败");
				}
				
			}
		}
		map.put("result", returnResult);
		return map;
	}
	
	/**
	 * 
	* @Description: app端保存支付单号 
	* @param orderid 订单id
	* @param defrayNumber 支付单号
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年8月21日 下午2:17:26     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult setDefrayNumber(String orderid,String defrayNumber,String channel){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(orderid);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("1")){
				returnResult.setKey("error");
				returnResult.setValue("订单状态不允许此操作");
			}else{
				orderForm.setDefrayNumber(defrayNumber);
				orderForm.setPaymentMethod(channel);
				personalOrderFormRepository.save(orderForm);
				returnResult.setKey("success");
	    		returnResult.setValue("保存支付单号成功");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 查询用户发生退款的订单 
	* @param userid 用户id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年8月24日 下午3:56:05     
	* @return List<ProvideOrderFormForOrder>    
	* @throws 
	 */
	public List<ProvideOrderFormForOrder> findRefundsOrders(String userid){
		return personalOrderFormDao.findRefundsOrders(userid);
	}
	
	/**
	 * 
	* @Description: 查询用户有效的优惠券 
	* @param userid 用户id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年8月28日 下午3:59:20     
	* @return List<Coupons>    
	* @throws 
	 */
	public Map findCouponsByPage(String userid, Integer pageNumber, Integer pageSize ,Integer orderBy){
		return personalOrderFormDao.findCouponsByPage(userid,pageNumber,pageSize,orderBy);
	}

	/* *
	 * @Description:分页查询用户已经使用的优惠券
	 * @author JTing
	 * @date 2017/11/22 14:21
	 * @param [userid, pageNumber, pageSize,orderBy]
	 * @return java.util.Map
	 */
	public Map findUsedCouponsByPage(String userid, Integer pageNumber, Integer pageSize,Integer orderBy){
		return personalOrderFormDao.findUsedCouponsByPage(userid,pageNumber,pageSize,orderBy);
	}


	/* *
	 * @Description:分页查询用户未使用已经过期的优惠卷
	 * @author JTing
	 * @date 2017/11/22 14:21
	 * @param [userid, pageNumber, pageSize,orderBy]
	 * @return java.util.Map
	 */
	public Map findExpiredCouponsByPage(String userid, Integer pageNumber, Integer pageSize,Integer orderBy){
		return personalOrderFormDao.findExpiredCouponsByPage(userid,pageNumber,pageSize,orderBy);
	}
	/* *
	 * @Description:根据活动id分页查询可用的优惠卷
	 * @author JTing
	 * @date 2018/03/15 10:35
	 * @param [acid, pageNumber, pageSize, orderBy]
	 * @return guoanmaker.personal.helper.common.AjaxJson
	 */
	public Map findUsefulCouponsForActiveByPage(String acid, Integer pageNumber, Integer pageSize, Integer orderBy) {
		ReturnResult returnResult = new ReturnResult();
		OperatorActivityEnlist operatorActivityEnlist = operatorActivityEnlistRepository.findOne(acid);
		if (operatorActivityEnlist==null) {
			returnResult.setKey("error");
			returnResult.setValue("未查到相关活动");
			HashMap map = new HashMap();
			map.put("result",returnResult);
			return map;
		}
		Double payMoney = operatorActivityEnlist.getPayMoney();
		if (payMoney==null || payMoney ==0) {
			HashMap map = new HashMap();
			map.put("total", 0);
			map.put("result", new ArrayList<Coupons>());
			return map;
		}
		return personalOrderFormDao.findUsefulCouponsForActiveByPage(operatorActivityEnlist.getUserId(),pageNumber,  pageSize,  orderBy, payMoney);

	}
	/* *
	 * @Description:根据活动id分页查询不可用的优惠卷
	 * @author JTing
	 * @date 2018/03/15 12:05
	 * @param [acid, pageNumber, pageSize, orderBy]
	 * @return java.util.Map
	 */
	public Map findNoUsefulCouponsForActiveByPage(String acid, Integer pageNumber, Integer pageSize, Integer orderBy) {
		ReturnResult returnResult = new ReturnResult();
		OperatorActivityEnlist operatorActivityEnlist = operatorActivityEnlistRepository.findOne(acid);
		if (operatorActivityEnlist==null) {
			returnResult.setKey("error");
			returnResult.setValue("未查到相关活动");
			HashMap map = new HashMap();
			map.put("result",returnResult);
			return map;
		}
		Double payMoney = operatorActivityEnlist.getPayMoney();
		if (payMoney==null || payMoney ==0) {
			//返回用户全部可用优惠卷 当作不可用优惠卷处理
			return personalOrderFormDao.findCouponsByPage(operatorActivityEnlist.getUserId(), pageNumber, pageSize, orderBy);
		}

		return personalOrderFormDao.findNoUsefulCouponsForActiveByPage(operatorActivityEnlist.getUserId(), pageNumber, pageSize, orderBy, payMoney);
	}
	/* *
	 * @Description:根据orderid分页查询可用的优惠卷
	 * @author JTing
	 * @date 2017/11/22 16:34
	 * @param [orderid, pageNumber, pageSize,orderBy]
	 * @return java.util.Map
	 */
	@Transactional
	public Map findUsefulCouponsByPage(String orderid,Integer pageNumber, Integer pageSize,Integer orderBy){
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(orderid);
		if (orderForm==null) {
			returnResult.setKey("error");
			returnResult.setValue("未查到相关订单");
			HashMap map = new HashMap();
			map.put("result",returnResult);
			return map;

		}
		ProvideCommodity commodity = orderForm.getCommodity();
		if (commodity == null) {

			returnResult.setKey("error");
			returnResult.setValue("未查到相关商品");
			HashMap map = new HashMap();
			map.put("result",returnResult);
			return map;

		}

		Boolean b = personalOrderFormDao.checkisroomOrderCommodity(commodity.getId());
		//是空间商品
		if (b) {
			HashMap map = new HashMap();
			map.put("total", 0);
			map.put("result", new ArrayList<Coupons>());
			return map;
		}

		//是秒杀商品
		String uid = orderForm.getUser().getId();
		String spikeid = orderForm.getSpikeid();
		if (spikeid!=null) {
			//if the order spikeid is not null,return the null map
			Map map = new HashMap();
			map.put("totle", 0);
			map.put("result", new ArrayList<Coupons>());
			return map;
		}
		String sid = operatorServerClassService.getTwoServiceTypeId(orderForm.getCommodity());
		//是行政服务商品
		Boolean isxz =personalOrderFormDao.checkisxingzcaigouOrderCommodity(sid);
		if (isxz) {
			return personalOrderFormDao.findUsefulCouponsByPageforxz(sid,uid,orderForm.getRealPrice(),pageNumber, pageSize,orderBy);

		}
		return personalOrderFormDao.findUsefulCouponsByPage(sid,uid,orderForm.getRealPrice(),pageNumber, pageSize,orderBy);
	}

	/* *
	 * @Description:根据orderid分页查询不可用的优惠卷
	 * @author JTing
	 * @date 2017/11/22 16:34
	 * @param @param [orderid, pageNumber, pageSize,orderBy]
	 * @return java.util.Map
	 */
	@Transactional
	public Map findNoUsefulCouponsByPage(String orderid,Integer pageNumber, Integer pageSize ,Integer orderBy){
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(orderid);
		if (orderForm==null) {
			returnResult.setKey("error");
			returnResult.setValue("未查到相关订单");
			HashMap map = new HashMap();
			map.put("result",returnResult);
			return map;

		}
		ProvideCommodity commodity = orderForm.getCommodity();
		if (commodity == null) {
			returnResult.setKey("error");
			returnResult.setValue("未查到相关商品");
			HashMap map = new HashMap();
			map.put("result",returnResult);
			return map;
		}

		String spikeid = orderForm.getSpikeid();
		String uid = orderForm.getUser().getId();

		Boolean b = personalOrderFormDao.checkisroomOrderCommodity(commodity.getId());
		//空间,秒杀 都应该走这个逻辑
		if (spikeid!=null || b) {
			//if the order spikeid is not null ,return all the useable coupons to the unuseable list
			return personalOrderFormDao.findCouponsByPage(uid, pageNumber, pageSize, orderBy);
		}
		String sid = operatorServerClassService.getTwoServiceTypeId(commodity);
		Boolean isxz = personalOrderFormDao.checkisxingzcaigouOrderCommodity(sid);
		//如果是行政采购的商品
		if (isxz) {
			return personalOrderFormDao.findNoUsefulCouponsByPageforxz(sid,uid,orderForm.getRealPrice(),pageNumber, pageSize,orderBy);
		}

		return personalOrderFormDao.findNoUsefulCouponsByPage(sid, uid,orderForm.getRealPrice(),pageNumber, pageSize,orderBy);
	}
	/* *
	 * @Description:查询用户可用,已用,过期的优惠卷的数目
	 * @author JTing  
	 * @date 2017/11/27 8:57  
	 * @param [userid]  
	 * @return java.util.Map  
	 */  
	public Map findAllTypeCouponsCountbyuserid(String userid) {
		return personalOrderFormDao.findAllTypeCouponsCountbyuserid(userid);
	}
	/**
	 * 
	* @Description: 查询用户已过期和已使用的优惠券
	* @param userid 用户id
	* @param pageNumber 分页页数，从0开始
	* @param pageSize 每页条数
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年11月14日 上午9:17:54     
	* @return Map    
	* @throws 
	 */
	public  Map findAllCouponsByPage(String userid, Integer pageNumber, Integer pageSize){
		return personalOrderFormDao.findAllCouponsByPage(userid, pageNumber, pageSize);
	}

	/* *
	 * @Description:获得用户领取的双12优惠卷id
	 * @author JTing
	 * @date 2017/12/01 9:00
	 * @param [userid]
	 * @return java.util.Map
	 */
	public Map getUser1212Coupons(String userid) {
		return  personalOrderFormDao.getUser1212Coupons(userid);
	}
	/**
	 * 
	* @Description: 分页查询用户有效的优惠券 
	* @param userid 用户id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年8月28日 下午3:59:20     
	* @return List<Coupons>    
	* @throws 
	 */
	public List<Coupons> findCoupons(String userid){
		return personalOrderFormDao.findCoupons(userid);
	}
	
	/**
	 * 
	* @Description: 验证是否符合使用优惠券，如果符合，将优惠券及订单信息进行更新 
	* @param orderid 订单id
	* @param couponid 优惠券id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年8月28日 下午9:15:09     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult orderToCoupon(String orderid,String couponid)throws Exception{
		
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(orderid);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
			Date date=sdf.parse(sdf.format(new Date()));
			if(couponid==null||couponid.equals("")){
				if(orderForm.getSpikeid()==null||orderForm.getSpikeid().equals("")){
					orderForm.setPreferentialMoney(0.00);
				}
				orderForm.setCouponid(couponid);
				personalOrderFormRepository.save(orderForm);
				returnResult.setKey("success");
	    		returnResult.setValue("验证成功");
			}else{
				double totleAmount=0;
				String mark="0";
				int percentage=Integer.parseInt(keyValueDao.findValue("direct_reduction_ratio"));
				String ids[]=couponid.split(",");
				if(ids.length==1){
					PersonalUserCoupon coupon = personalUserCouponRepository.findOne(ids[0]);
					if(coupon!=null){
						if(coupon.getOperatorCoupon().getCouponstype().equals("1")){
							if(coupon.getOperatorCoupon().getFullamount()<=orderForm.getRealPrice()&&!coupon.getIsUsed().equals("1")&&!coupon.getExpiredDate().before(date)&&!coupon.getStartDate().after(date)&&(coupon.getOperatorCoupon().getServerid()==null||coupon.getOperatorCoupon().getServerid().equals("0")||coupon.getOperatorCoupon().getServerid().equals(operatorServerClassService.getTwoServiceTypeId(orderForm.getCommodity())))){
								orderForm.setCouponid(couponid);
								orderForm.setCouponName(coupon.getOperatorCoupon().getCouponsname());
								orderForm.setPreferentialMoney(coupon.getOperatorCoupon().getSubamount());
								personalOrderFormRepository.save(orderForm);
								returnResult.setKey("success");
					    		returnResult.setValue("验证成功");
							}else{
								returnResult.setKey("error");
					    		returnResult.setValue("优惠券不符合使用条件");
							}
						}else if(coupon.getOperatorCoupon().getCouponstype().equals("0")){
							totleAmount=coupon.getOperatorCoupon().getLapseamount();
						}
					}else{
						returnResult.setKey("error");
			    		returnResult.setValue("优惠券不符合使用条件");
					}
				}else{
					for (int i = 0; i < ids.length; i++) {
						PersonalUserCoupon coupon = personalUserCouponRepository.findOne(ids[i]);
						if(!coupon.getOperatorCoupon().getCouponstype().equals("0")){
				    		mark="1";
				    		break;
						}else{
							if(!coupon.getIsUsed().equals("1")&&!coupon.getExpiredDate().before(date)&&!coupon.getStartDate().after(date)&&(coupon.getOperatorCoupon().getServerid()==null||coupon.getOperatorCoupon().getServerid().equals("0")||coupon.getOperatorCoupon().getServerid().equals(operatorServerClassService.getTwoServiceTypeId(orderForm.getCommodity())))){
								totleAmount+=coupon.getOperatorCoupon().getLapseamount();
							}else{
					    		mark="1";
					    		break;
							}
						}
					}
				}
				if(mark.equals("1")||totleAmount>orderForm.getRealPrice()*percentage/100){
					returnResult.setKey("error");
		    		returnResult.setValue("优惠券不符合使用条件");
				}else{
					orderForm.setCouponid(couponid);
					if(totleAmount>0){
						orderForm.setCouponName("直减优惠券");
						orderForm.setPreferentialMoney(totleAmount);
					}
					personalOrderFormRepository.save(orderForm);
					returnResult.setKey("success");
		    		returnResult.setValue("验证成功");
				}
			}
		}
		
		return returnResult;
		
		
	}

	/**
	 * 
	* @Description: 初始化truePrice
	* @param 
	* @author Yvonne_MGL 
	* @date 2017年11月13日 上午10:35:24     
	* @return void    
	* @throws 
	 */
	@Transactional
	public void initializeTruePrice(){
		List<ProvideOrderForm> list=personalOrderFormRepository.findAll();
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				ProvideOrderForm orderForm=list.get(i);
				if(orderForm.getOrderStatus().equals("8")||orderForm.getOrderStatus().equals("10")||orderForm.getOrderStatus().equals("11")||orderForm.getOrderStatus().equals("12")){
					if(orderForm.getPreferentialMoney()!=null){
						orderForm.setTruePrice(orderForm.getRealPrice()+orderForm.getPreferentialMoney()+orderForm.getRefundsAmount());
					}else{
						orderForm.setTruePrice(orderForm.getRealPrice()+orderForm.getRefundsAmount());
					}
				}else{
					orderForm.setTruePrice(orderForm.getRealPrice());
				}
			}
			
		}
	}
	
	/**
	 * 
	* @Description: 创建一口价商品的秒杀订单 
	* @param userid 用户id
	* @param spikeid 秒杀id
	* @param contactPerson 联系人
	* @param contactNumber 联系电话
	* @param requirementDescription 需求描述
	* @param placeOrderType 下单渠道
	* @param serverPlace 服务区域
	* @param rangeid 
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年11月22日 下午3:09:19     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult createSpikeNotBargainingOrder(String userid,String spikeid,String contactPerson,String contactNumber,String requirementDescription,String placeOrderType,String serverPlace,String rangeid){
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=new ProvideOrderForm();
		
		OperatorSecckill secckill=operatorSecckillRepository.findOne(spikeid);
		Date now=new Date();
		if(secckill.getSkStartTime().after(now)){
			returnResult.setKey("error");
			returnResult.setValue("秒杀活动未开始");
		}else if(secckill.getSkEndTime().before(now)){
			returnResult.setKey("error");
			returnResult.setValue("秒杀活动已结束");
		}else if(secckill.getSkNum()==null||secckill.getSkNum()==0){
			returnResult.setKey("error");
			returnResult.setValue("秒杀商品已抢光");
		}else{
			ProvideCommodity provideCommodity=provideCommodityRepository.findOne(secckill.getCommodId());
			if(provideCommodity!=null&&provideCommodity.getStock()!=null&&provideCommodity.getStock()>0&&provideCommodity.getCommodityState()==2){
				provideCommodity.setStock(provideCommodity.getStock()-1);
				if(provideCommodity.getSalesVolume()==null){
					provideCommodity.setSalesVolume(1);
				}else{
					provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()+1);
				}
				if(provideCommodity.getStock()==0){
					provideCommodity.setCommodityState(4);
				}
				if(provideCommodity.getStock()==0&&provideCommodity.getType().equals("3")){
					provideCommodity.setCommodityState(7);
				}
				provideCommodityRepository.save(provideCommodity);
				if(rangeid!=null&&!rangeid.equals("")){
					ProvideCommodityServiceRange range=provideCommodityServiceRangeRepository.findOne(rangeid);
					if(range!=null){
						orderForm.setRealPrice(range.getFinalPrice());
						orderForm.setTruePrice(range.getFinalPrice());
						orderForm.setUnitPrice(range.getCommodityPrice());
					}else{
						orderForm.setRealPrice(provideCommodity.getFinalPrice());
						orderForm.setTruePrice(provideCommodity.getFinalPrice());
						orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
					}
				}else{
					orderForm.setRealPrice(provideCommodity.getFinalPrice());
					orderForm.setTruePrice(provideCommodity.getFinalPrice());
					orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
				}
				
				orderForm.setOrderNumber(personalOrderFormDao.getOrderNumber());
				orderForm.setOrderStatus("1");
				orderForm.setContactPerson(contactPerson);
				orderForm.setContactNumber(contactNumber);
				orderForm.setRequirementDescription(requirementDescription);
				orderForm.setPlaceOrderTime(new Date());
				orderForm.setQuantity(1);
				orderForm.setOrderType("1");
				orderForm.setUser(personalUserRepository.findOne(userid));
				orderForm.setCommodity(provideCommodity);
				orderForm.setIsRead("0");
				orderForm.setPlaceOrderType(placeOrderType);
				orderForm.setServerPlace(serverPlace);
				orderForm.setPreferentialMoney(secckill.getSkPriceDiffer());
				orderForm.setSpikeid(spikeid);
				orderForm.setSpikePrice(secckill.getSkPrice());
				personalOrderFormRepository.save(orderForm);
				
				secckill.setSkNum(secckill.getSkNum()-1);
				if(secckill.getSkSellNum()==null){
					secckill.setSkSellNum(1);
				}else{
					secckill.setSkSellNum(secckill.getSkSellNum()+1);
				}
				operatorSecckillRepository.save(secckill);
				
				returnResult.setKey("success");
	    		returnResult.setValue(orderForm.getId());
			}else{
				if(provideCommodity==null){
					returnResult.setKey("error");
					returnResult.setValue("商品不存在");
				}else if(provideCommodity.getStock()==null||provideCommodity.getStock()<=0){
					returnResult.setKey("error");
					returnResult.setValue("商品库存不足");
				}else if(provideCommodity.getCommodityState()==4){
					returnResult.setKey("error");
					returnResult.setValue("商品已下架");
				}else if(provideCommodity.getCommodityState()==5){
					returnResult.setKey("error");
					returnResult.setValue("商品已被冻结");
				}else if(provideCommodity.getCommodityState()==6){
					returnResult.setKey("error");
					returnResult.setValue("商品已被删除");
				}else{
					returnResult.setKey("error");
					returnResult.setValue("商品当前状态不允许下单");
				}
				
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 创建工位租用秒杀订单 
	* @param userid 用户id
	* @param spikeid 秒杀id
	* @param contactPerson 联系人
	* @param contactNumber 联系电话
	* @param beginDate 租用起始时间
	* @param endDate 租用结束时间
	* @param quantity 数量
	* @param remark 
	* @param placeOrderType
	* @param serverPlace
	* @param @return
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年11月22日 下午4:13:36     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult createSpikeSeatLeaseOrder(String userid,String spikeid,String contactPerson,String contactNumber,String beginDate,String endDate,int quantity,String remark,String placeOrderType,String serverPlace)throws Exception{
		ReturnResult returnResult = new ReturnResult();
		ProvideOrderForm orderForm=new ProvideOrderForm();
		
		OperatorSecckill secckill=operatorSecckillRepository.findOne(spikeid);
		Date now=new Date();
		if(secckill.getSkStartTime().after(now)){
			returnResult.setKey("error");
			returnResult.setValue("秒杀活动未开始");
		}else if(secckill.getSkEndTime().before(now)){
			returnResult.setKey("error");
			returnResult.setValue("秒杀活动已结束");
		}else if(secckill.getSkNum()==null||secckill.getSkNum()-quantity<0){
			returnResult.setKey("error");
			returnResult.setValue("秒杀商品已抢光");
		}else{
			ProvideCommodity provideCommodity=provideCommodityRepository.findOne(secckill.getCommodId());
			if(provideCommodity!=null&&provideCommodity.getStock()!=null&&(provideCommodity.getStock()-quantity)>=0&&provideCommodity.getCommodityState()==2){
				int days=SystemHelper.daysBetween(beginDate, endDate);
				if(days<=0){
					returnResult.setKey("error");
					returnResult.setValue("租用天数不符合要求");
				}else{
					provideCommodity.setStock(provideCommodity.getStock()-quantity);
					if(provideCommodity.getSalesVolume()==null){
						provideCommodity.setSalesVolume(quantity);
					}else{
						provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()+quantity);
					}
					if(provideCommodity.getStock()==0){
						provideCommodity.setCommodityState(4);
					}
					provideCommodityRepository.save(provideCommodity);
					orderForm.setRealPrice(provideCommodity.getFinalPrice()*quantity*days);
					orderForm.setTruePrice(provideCommodity.getFinalPrice()*quantity*days);
					orderForm.setRentedBeginDate(beginDate);
					orderForm.setRentedEndDate(endDate);
					orderForm.setUnitPrice(provideCommodity.getCommodityPrice());
					orderForm.setOrderNumber(personalOrderFormDao.getOrderNumber());
					orderForm.setOrderStatus("1");
					orderForm.setContactPerson(contactPerson);
					orderForm.setContactNumber(contactNumber);
					orderForm.setRequirementDescription(remark);
					orderForm.setPlaceOrderTime(new Date());
					orderForm.setQuantity(quantity);
					orderForm.setOrderType("3");
					orderForm.setUser(personalUserRepository.findOne(userid));
					orderForm.setCommodity(provideCommodity);
					orderForm.setIsRead("0");
					orderForm.setPlaceOrderType(placeOrderType);
					orderForm.setServerPlace(serverPlace);
					orderForm.setPreferentialMoney(secckill.getSkPriceDiffer()*quantity*days);
					orderForm.setSpikeid(spikeid);
					orderForm.setSpikePrice(secckill.getSkPrice()*quantity*days);
					personalOrderFormRepository.save(orderForm);
					secckill.setSkNum(secckill.getSkNum()-quantity);
					if(secckill.getSkSellNum()==null){
						secckill.setSkSellNum(quantity);
					}else{
						secckill.setSkSellNum(secckill.getSkSellNum()+quantity);
					}
					operatorSecckillRepository.save(secckill);
					returnResult.setKey("success");
		    		returnResult.setValue(orderForm.getId());
				}
				
				
			}else{
				if(provideCommodity==null){
					returnResult.setKey("error");
					returnResult.setValue("商品不存在");
				}else if(provideCommodity.getStock()==null||provideCommodity.getStock()-quantity<0){
					returnResult.setKey("error");
					returnResult.setValue("商品库存不足");
				}else if(provideCommodity.getCommodityState()==4){
					returnResult.setKey("error");
					returnResult.setValue("商品已下架");
				}else if(provideCommodity.getCommodityState()==5){
					returnResult.setKey("error");
					returnResult.setValue("商品已被冻结");
				}else if(provideCommodity.getCommodityState()==6){
					returnResult.setKey("error");
					returnResult.setValue("商品已被删除");
				}else{
					returnResult.setKey("error");
					returnResult.setValue("商品当前状态不允许下单");
				}
			}
		}
		
		
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 查询用户各个状态的订单数量 
	* @param userid 用户id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2018年1月5日 下午2:55:35     
	* @return Map    
	* @throws 
	 */
	public Map getOrderStateNum(String userid){
		return personalOrderFormDao.getOrderStateNum(userid);
	}

	/**
	 * 
	* @Description: 验证订单是否可以支付 
	* @param orderid 订单id
	* @param sumPrice  订单的总价格，单位为分
	* @param preferentialPrice 优惠价格，单位为分
	* @param @return
	* @author Yvonne_MGL 
	* @date 2018年3月5日 上午10:51:36     
	* @return AjaxJson    
	* @throws 
	 */
	public ReturnResult verifyOrder(String orderid,Integer sumPrice,Integer preferentialPrice){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=personalOrderFormRepository.findOne(orderid);
		if(orderForm!=null){
			int preferentialMoney=0;
			if(orderForm.getPreferentialMoney()!=null){
				preferentialMoney=Integer.parseInt(new DecimalFormat("#").format(orderForm.getPreferentialMoney()*100));
			}
			int realPrice=0;
			if(orderForm.getRealPrice()!=null){
				realPrice=Integer.parseInt(new DecimalFormat("#").format(orderForm.getRealPrice()*100));
			}
			if(preferentialMoney==preferentialPrice&&realPrice==sumPrice){
				returnResult.setKey("success");
				returnResult.setValue("订单可以支付");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("订单不符合支付条件");
			}
		}
		else {
			OperatorActivityEnlist activityEnlist=operatorActivityEnlistRepository.findOne(orderid);
			if(activityEnlist !=null){
				if(activityEnlist.getCouponPrice()==null ||activityEnlist.getCouponPrice().equals("")==true ) {
					activityEnlist.setCouponPrice(0.0);
				}
				BigDecimal payMoney = new BigDecimal(activityEnlist.getPayMoney()).multiply(new BigDecimal(100));
				BigDecimal couponPrice = new BigDecimal(activityEnlist.getCouponPrice()).multiply(new BigDecimal(100));
				if(payMoney.intValue()==sumPrice && couponPrice.intValue()== preferentialPrice ){
					returnResult.setKey("success");
					returnResult.setValue("订单可以支付");
				}else{
					returnResult.setKey("error");
					returnResult.setValue("订单不符合支付条件");
				}
			}else{
				returnResult.setKey("error");
				returnResult.setValue("订单不存在");
			}
			
		}
		return returnResult;
	}

}
